package com.travel.server.manager.impl.command.project;

import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CollectionUtil;
import com.travel.server.manager.dto.request.project.UpdateProjectGroupRequest;
import com.travel.server.manager.dto.response.EmptyResponse;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.GroupDal;
import com.travel.server.manager.impl.dal.GroupDal.GroupParam;
import com.travel.server.manager.impl.dal.ProjectDal;
import com.travel.server.manager.impl.enums.GroupEnum;
import com.travel.server.manager.model.ProjectGroup;
import com.travel.server.manager.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/10/26 17:45
 * @Desc:
 */
@Component
@Slf4j
public class UpdateProjectGroupCommand extends AbstractCommand<UpdateProjectGroupRequest, EmptyResponse> {

    @Autowired
    private GroupDal groupDal;

    @Autowired
    private ProjectDal projectDal;

    @Override
    protected void checkInput(UpdateProjectGroupRequest request) {
        if(request.getId() == null){
            throwInvalidParam();
        }
    }

    @Override
    public EmptyResponse handle(UpdateProjectGroupRequest request) {
        checkInput(request);

        ProjectGroup projectGroup = groupDal.selectById(request.getId());
        if(projectGroup == null){
            throw new WorkException(WorkCode.RECORD_NOT_EXIST);
        }

        //修改了项目分组的名称，需要验证是否重复
        if(!projectGroup.getName().equals(request.getGroupName())){
            GroupParam param = new GroupParam();
            param.setName(request.getGroupName());
            List<ProjectGroup> list = groupDal.selectByExample(param);
            if(!CollectionUtil.isEmpty(list)){
                throw new WorkException(WorkCode.EXIST_SAME_NAME);
            }
        }

        UserInfo userInfo = getUserInfo();
        Date now = new Date();

        if(projectGroup.getParentClass().equals(GroupEnum.PROJECT.getType())){
            projectDal.updateProject(projectGroup.getName(), request.getGroupName());
        }else if(projectGroup.getParentClass().equals(GroupEnum.PROJECT_TYPE.getType())){
            projectDal.updateProjectType(projectGroup.getName(), request.getGroupName());
        }

        projectGroup.setNumber(request.getNumber());
        projectGroup.setName(request.getGroupName());
        projectGroup.setParentClass(request.getParentClass());
        projectGroup.setUpdateTime(now);
        projectGroup.setUpdateBy(userInfo.getName());
        groupDal.updateOrInsert(projectGroup);

        return new EmptyResponse();
    }
}
